package org.zoomdev.zoom.http;

import okhttp3.OkHttpClient;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

class DefaultOkHttpClient implements HttpClient {

    public static final int DEFAULT_CONNECT_TIMEOUT = 5;

    public static final int DEFAULT_READ_TIMEOUT = 30;


    public OkHttpClient client;

    public DefaultOkHttpClient() {
        this(DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT);
    }


    public DefaultOkHttpClient(int connectTimeout, int readTimeout, SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) {
        client = new OkHttpClient().newBuilder().hostnameVerifier((hostname, session) -> true)
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .sslSocketFactory(sslSocketFactory, trustManager)
                .build();
    }

    public DefaultOkHttpClient(int connectTimeout, int readTimeout) {
        client = new OkHttpClient().newBuilder().hostnameVerifier((hostname, session) -> true)
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS).build();
    }


    @Override
    public Response execute(Request request) throws IOException {
        okhttp3.Response resp = client.newCall(request.build()).execute();
        return new Response(request, resp);
    }
}
